#include <interrupt/interrupt.h>
#include <io.h>
#include <device/pic.h>
#include <thread/thread.h>

#include <service.h>

extern uint64_t global_ticks;
PRIVATE void intr_HPETtimer_handler()
{
    eoi(0x20);
    global_ticks++;
    task_struct_t* cur_thread = running_thread();
    cur_thread->elapsed_ticks++;
    if (cur_thread->ticks == 0)
    {
        schedule();
    }
    else
    {
        cur_thread->ticks--;
    }
    return;
}

void init_pit()
{
    uint8_t *HPET_addr = (uint8_t *)KADDR_P2V(0xfed00000);

    *(uint64_t*)(HPET_addr +  0x10) = 3;
    io_mfence();

    *(uint64_t*)(HPET_addr + 0x100) = 0x004c;
    io_mfence();

    // 1000000 / 69.841279 => 14318.17 = 1 ms
    *(uint64_t*)(HPET_addr + 0x108) = 1000000 / 70;
    io_mfence();

    *(uint64_t*)(HPET_addr + 0xf0) = 0;
    io_mfence();
    global_ticks = 0;
    register_handle(0x20,intr_HPETtimer_handler);
}